package com.jpush.customer.service;

import com.jpush.customer.feign.KeplerClient;
import com.jpush.customer.pojo.V1CsdAppTopDetailReqDTO;
import com.jpush.customer.pojo.V1CsdNestAppCrowdCreateReqDTO;
import feign.Response;
import feign.form.util.CharsetUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

@Service
public class CustomerService {

    @Autowired
    private KeplerClient keplerClient;

    public String multiFile( MultipartFile[] file) throws IOException {
        keplerClient.multiFile(file);
        return "upload task";
    }


    public String createTask(V1CsdNestAppCrowdCreateReqDTO reqDTO,  MultipartFile file) throws IOException {
        keplerClient.param(reqDTO);
        return "upload task";
    }

    public void export(V1CsdAppTopDetailReqDTO reqDTO, HttpServletResponse httpServletResponse) throws IOException {

        Response response = keplerClient.appTopExport(reqDTO);
        Response.Body body = response.body();
        Map<String, Collection<String>> headers = response.headers();
        for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) {
            String key = entry.getKey();
            String val = getHeadFirst(entry.getValue());
            httpServletResponse.setHeader(key, val );
        }

        try {
            OutputStream outputStream = httpServletResponse.getOutputStream();
            InputStream inputStream = body.asInputStream();
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getHeadFirst(Collection<String> names ){
        String fileName = null;
        for (String name : names) {
            fileName = name;
            break;
        }
        return fileName;
    }
}
